<?php
/**
 * Created by PhpStorm
 * User: shen.zk
 * Date: 2023/9/5
 * Time: 09:38
 * Comment: ''
 */

namespace App\Http\Middleware;

use App\Common\Constant;
use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use App\Service\Common\CheckSignService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Closure;

class CheckTokenMiddleware extends BaseMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        // 获取商户公钥
        $access_mid = request('access_mid');
        $cacheInfo = Redis::get(Constant::MERCHANTID.':'.$access_mid);
        $cacheMerchants = json_decode($cacheInfo,true);
        $publicKey = $cacheMerchants['public_key'];

        // 获取平台自身私钥
        $privateKeyPath = config('selfpem.self_private');
        $privateKey = file_get_contents($privateKeyPath);

        // 加密加签名
        $responseArr = ['error_code' => 401, 'error_msg' => "请前往登入",'timestamp'=>time()];
        $res = CheckSignService::getInstance()->selfRequestCreateSign($responseArr,$publicKey,$privateKey);
        $res['error_code'] = 401;
        $res['error_msg'] = '请前往登入';
        try {
            // 验证token是否存在
            $this->checkForToken($request);

            // 校验用户
            $user = auth('api')->user();
            Log::info("[会话中间件]获取用户信息".json_encode($user));
            if (empty($user))
            {
                $response = response(json_encode($res),'200');
                return $response->header('Content-Type', "json");
            }
            if ($user->status == 2)
            {
                $res['error_code'] = ResponseCode::USER_DISABLE[0];
                $res['error_msg'] = ResponseCode::USER_DISABLE[1];
                $response = response(json_encode($res),'200');
                return $response->header('Content-Type', "json");
            }
            // 获取token
            $tokenStr = $request->header('Authorization');
            $token = str_replace('Bearer ', '', $tokenStr);
            if(empty($tokenStr) || !str_contains($tokenStr, 'Bearer ') || empty($token))
                throw new BusinessException(ResponseCode::API_AUTH_FORBIDDEN);

            // 重写用户ID
            $request->offsetSet("member_id",$user->id);
            return $next($request);
        }catch (\Exception $e){
            Log::info("[会话中间件]token错误信息".$e->getMessage().$e->getFile().$e->getLine());
            $res['error_msg'] = '会话解析服务异常';
            $$response = response(json_encode($res),'200');
            return $response->header('Content-Type', "json");
        }

    }
}
